 " vim: fdm=marker cms="%s

" Ale:{{{
try
	let g:ale_root = get(g:, 'ale_root', {})
	let g:ale_linters = get(g:, 'ale_linters', {'c++': ['clang'], 'python': ['pylint']})
	let g:ale_matlab_mlint_executable = executable('mlint') ? 'mlint' : 'C:\Programs\MATLAB\R2020b\bin\win64\mlint.exe' 
	let g:ale_sign_error = get(g:, 'ale_sign_error', '✗')
	let g:ale_sign_warning = get(g:, 'ale_sign_warning', '⚡')
	if filereadable(g:ale_matlab_mlint_executable)
		let $PATH = fnamemodify(g:ale_matlab_mlint_executable, ':p:h') . ';' . $PATH
	endif
	packadd ale
endtry
if exists('g:loaded_ale_dont_use_this_in_other_plugins_please')
	" ALEDisable
	ALEEnable
endif
"}}}

" AsyncRun:{{{
try
	packadd asyncrun.vim
endtry
"}}}

" AsyncTasks:{{{
try
	packadd asynctasks.vim
endtry
"}}}

" AutoCompletePopup{{{
try
	packadd AutoComplPop
endtry
if exists('g:loaded_acp')
	AcpEnable
endif
"}}}

" Bookmarks:{{{
let g:bookmark_no_default_key_mappings = 0
let g:bookmark_sign = '>>'	
let g:bookmark_annotation_sign = '##'
let g:bookmark_highlight_lines = 1
let g:bookmark_location_list = 1
try
	packadd vim-bookmarks
endtry
if exists('g:bm_has_any')
  nmap mm <Plug>BookmarkToggle
  nmap mi <Plug>BookmarkAnnotate
  nmap ma <Plug>BookmarkShowAll
  nmap mj <Plug>BookmarkNext
  nmap mk <Plug>BookmarkPrev
  nmap mc <Plug>BookmarkClear
  nmap mx <Plug>BookmarkClearAll
  " " these will also work with a [count] prefix
  nmap mK <Plug>BookmarkMoveUp
  nmap mJ <Plug>BookmarkMoveDown
  nmap mg <Plug>BookmarkMoveToLine
  " highlight BookmarkSign ctermbg=whatever ctermfg=whatever
  " highlight BookmarkAnnotationSign ctermbg=whatever ctermfg=whatever
  " highlight BookmarkLine ctermbg=whatever ctermfg=whatever
  " highlight BookmarkAnnotationLine ctermbg=whatever ctermfg=whatever
endif
"}}}

" BufExplorer:{{{
try
	packadd bufexplorer
endtry
if get(g:, 'bufexplorer_version', 0)
	nnoremap <m-b>	:BufExplorer<cr>
endif
"}}}

" Bufferline{{{
try
	packadd vim-bufferline
endtry
if exists('g:loaded_bufferline') && g:loaded_bufferline
endif
"}}}

" Coc.nvim{{{
try
	let g:coc_enabled = v:false
	if exists('g:coc_enabled') && g:coc_enabled && !exists('g:did_coc_loaded')
		packadd coc.nvim
	endif
endtry
if exists('g:did_coc_loaded') && g:did_coc_loaded
	" Show hover when provider exists, fallback to vim's builtin behavior.
	function! ShowDocumentation()
		if CocAction('hasProvider', 'hover')
			call CocActionAsync('definitionHover')
		else
			call feedkeys('K', 'in')
		endif
	endfunction
	nnoremap <silent> K :call ShowDocumentation()<CR>
	nnoremap <F3> :CocList --top marketplace<cr>
	let g:coc_global_extensions = ['coc-json', 'coc-git', 'coc-diagnostic']
	" navigate chunks of current buffer
	nmap [g <Plug>(coc-git-prevchunk)
	nmap ]g <Plug>(coc-git-nextchunk)
	" navigate conflicts of current buffer
	nmap [c <Plug>(coc-git-prevconflict)
	nmap ]c <Plug>(coc-git-nextconflict)
	" show chunk diff at current position
	nmap gs <Plug>(coc-git-chunkinfo)
	" show commit contains current position
	nmap gc <Plug>(coc-git-commit)
	" create text object for git chunks
	omap ig <Plug>(coc-git-chunk-inner)
	xmap ig <Plug>(coc-git-chunk-inner)
	omap ag <Plug>(coc-git-chunk-outer)
	xmap ag <Plug>(coc-git-chunk-outer)
	" nnoremap <silent> <leader>g  :<C-u>CocList --normal gstatus<CR>
endif
"}}}

" Commentary:{{{
try
	packadd vim-commentary 
endtry
if exists('g:loaded_commentary')
	nnoremap <m-;> 	:Commentary<cr>
	vnoremap <m-;> 	:Commentary<cr>
endif
"}}}

" CtrlP: {{{
try
	packadd ctrlp.vim
endtry
if get(g:, 'loaded_ctrp', 0)
endif
"}}}

" EasyAlign:{{{
try
	packadd vim-easy-align
endtry
if exists("g:loaded_easy_align_plugin")
	xmap ga <Plug>(EasyAlign)
	nmap ga <Plug>(EasyAlign)
endif
"}}}

" EasyMotion:{{{
try
	packadd vim-easymotion
endtry
if exists('g:EasyMotion_loaded')
    map <Leader>y <Plug>(easymotion-prefix)
endif
"}}}

" Fzf:{{{
" An action can be a reference to a function that processes selected lines
function! s:build_quickfix_list(lines)
	call setqflist(map(copy(a:lines), '{ "filename": v:val, "lnum": 1 }'))
	copen
	cc
endfunction

let g:fzf_action = {
			\ 'ctrl-q': function('s:build_quickfix_list'),
			\ 'ctrl-t': 'tab split',
			\ 'ctrl-x': 'split',
			\ 'ctrl-v': 'vsplit' }

" Default fzf layout
" - Popup window (center of the screen)
let g:fzf_layout = { 'window': { 'width': 0.9, 'height': 0.6 } }

" Customize fzf colors to match your color scheme
" - fzf#wrap translates this to a set of `--color` options
let g:fzf_colors = { 
			\ 'fg':      ['fg', 'Normal'],
			\ 'bg':      ['bg', 'Normal'],
			\ 'hl':      ['fg', 'Comment'],
			\ 'fg+':     ['fg', 'CursorLine', 'CursorColumn', 'Normal'],
			\ 'bg+':     ['bg', 'CursorLine', 'CursorColumn'],
			\ 'hl+':     ['fg', 'Statement'],
			\ 'info':    ['fg', 'PreProc'],
			\ 'border':  ['fg', 'Ignore'],
			\ 'prompt':  ['fg', 'Conditional'],
			\ 'pointer': ['fg', 'Exception'],
			\ 'marker':  ['fg', 'Keyword'],
			\ 'spinner': ['fg', 'Label'],
			\ 'header':  ['fg', 'Comment'] }

" Enable per-command history
" - History files will be stored in the specified directory
" - When set, CTRL-N and CTRL-P will be bound to 'next-history' and
"   'previous-history' instead of 'down' and 'up'.
let g:fzf_history_dir = '~/.local/share/fzf-history'

let g:fzf_vim = get(g:, 'fzf_vim', {})
let g:fzf_vim.command_prefix = 'Fzf'
" This is the default option:
"   - Preview window on the right with 50% width
"   - CTRL-/ will toggle preview window.
" - Note that this array is passed as arguments to fzf#vim#with_preview function.
" - To learn more about preview window options, see `--preview-window` section of `man fzf`.
" let g:fzf_vim.preview_window = ['right,50%', 'ctrl-/']
" Preview window is hidden by default. You can toggle it with ctrl-/.
" It will show on the right with 50% width, but if the width is smaller
" than 70 columns, it will show above the candidate list
" let g:fzf_vim.preview_window = ['hidden,right,50%,<70(up,40%)', 'ctrl-/']
let g:fzf_vim.preview_window = ['right,50%,<70(up,40%)', 'ctrl-/']

" fzf.vim needs bash to display the preview window.
" On Windows, fzf.vim will first see if bash is in $PATH, then if
" Git bash (C:\Program Files\Git\bin\bash.exe) is available.
" If you want it to use a different bash, set this variable.
"   let g:fzf_vim = {}
"   let g:fzf_vim.preview_bash = 'C:\Git\bin\bash.exe'
let g:fzf_vim.preview_bash = 'C:\Programs\Git\bin\bash.exe'

" [Buffers] Jump to the existing window if possible
let g:fzf_vim.buffers_jump = 1

" [[B]Commits] Customize the options used by 'git log':
let g:fzf_vim.commits_log_options = '--graph --color=always --format="%C(auto)%h%d %s %C(black)%C(bold)%cr"'

" [Tags] Command to generate tags file
let g:fzf_vim.tags_command = 'ctags -R'

" [Commands] --expect expression for directly executing the command
let g:fzf_vim.commands_expect = 'alt-enter,ctrl-x'

try
	packadd fzf
	packadd fzf.vim
endtry
if get(g:, 'loaded_fzf_vim', 0)
	nnoremap <m-f> :FzfFiles<cr>
	" nnoremap <m-h> :Helptags<cr>
endif
"}}}

" gruvbox{{{
try
	packadd gruvbox
	colorscheme gruvbox
endtry
"}}}

" Gvimfullscreen:{{{
try
	packadd gvimfullscreen
endtry
if exists('g:loaded_gvimfullscreen') && g:loaded_gvimfullscreen
	nnoremap <M-CR> 	:ToggleFullScreen<cr>
	nnoremap <F11> 		:ToggleFullScreen<cr>
endif
"}}}

" Git:{{{
try
	" packadd lazygit.nvim
	packadd vim-fugitive
endtry
" if get(g:, 'loaded_lazygit_vim', 0)
if get(g:, 'loaded_fugitive', 0)
	nmap <Plug>(git-status) :Git status<cr>
	nmap <Plug>(git-prefix)s <Plug>(git-status)
	nmap <Plug>(git-diff) :Git diff<cr>
	nmap <Plug>(git-prefix)d <Plug>(git-diff)
	nmap <Plug>(git-add) :Git add .<cr>
	nmap <Plug>(git-prefix)a <Plug>(git-add)
	nmap <Plug>(git-commit) :Git commit<cr>
	nmap <Plug>(git-prefix)c <Plug>(git-commit)
	nmap <Plug>(git-push) :Git push<cr>
	nmap <Plug>(git-prefix)p <Plug>(git-push)
	nmap <Plug>(git-pull) :Git pull<cr>
	nmap <Plug>(git-prefix)l <Plug>(git-pull)
	nmap <M-g> :G<cr>
endif
"}}}

" LeaderF:{{{
try
	let g:Lf_PythonVersion = 3
	let g:Lf_ShortCutF = '<leader>f'
	let g:Lf_ShortCutB = '<leader>b'
	let g:Lf_HistoryExclude = {
				\ 'cmd': ['^w!?', '^q!?', '^.\s*$'],
				\ 'search': ['^Plug']
				\}
	if has('python3')
		packadd LeaderF
		packadd LeaderF-git
		packadd LeaderF-everything
	endif
endtry
if get(g:, 'leaderf_loaded', 0)
	nnoremap <leader>b :<C-u>LeaderfBuffer<cr>
	nnoremap <leader>f :<C-u>LeaderfFile<cr>
	nnoremap <leader>F :<C-u>LeaderfFunction<cr>
	nnoremap <leader>/ :<C-u>LeaderfRgInteractive<cr>
	nnoremap <leader>? :<C-u>LeaderfHelp<cr>
	nnoremap <leader>l :<C-u>LeaderfSelf<cr>
	nnoremap <leader>r :<C-u>LeaderfMru<cr>
	nnoremap <leader>: :<C-u>LeaderfCommand<cr>
	" git{{{
	let g:Lf_GitCommands = [
				\ {"Leaderf git diff":                         "fuzzy search and view the diffs"},
				\ {"Leaderf git diff --side-by-side":          "fuzzy search and view the side-by-side diffs"},
				\ {"Leaderf git diff --side-by-side --current-file":"view the side-by-side diffs of the current file"},
				\ {"Leaderf git diff --explorer":              "view the diffs in an explorer tabpage"},
				\ {"Leaderf git diff --explorer --unified":    "view the diffs in an explorer tabpage, the diffs is shown in unified view"},
				\ {"Leaderf git diff --directly":              "view the diffs directly"},
				\ {"Leaderf git diff --directly --position right":"view the diffs in the right split window"},
				\ {"Leaderf git diff --cached":                "fuzzy search and view `git diff --cached`"},
				\ {"Leaderf git diff --cached --side-by-side": "fuzzy search and view the side-by-side diffs of `git diff --cached`"},
				\ {"Leaderf git diff --cached --explorer":     "view `git diff --cached` in an explorer tabpage"},
				\ {"Leaderf git diff --cached --directly":     "view `git diff --cached` directly"},
				\ {"Leaderf git diff --cached --directly --position right": "view `git diff --cached` directly in the right split window"},
				\ {"Leaderf git diff HEAD":                    "fuzzy search and view `git diff HEAD`"},
				\ {"Leaderf git diff HEAD --side-by-side":     "fuzzy search and view the side-by-side diffs of `git diff HEAD`"},
				\ {"Leaderf git diff HEAD --explorer":         "view `git diff HEAD` in an explorer tabpage"},
				\ {"Leaderf git diff HEAD --directly":         "view `git diff HEAD` directly"},
				\ {"Leaderf git diff HEAD --directly --position right":     "view `git diff HEAD` directly in the right split window"},
				\ {"Leaderf git log":                          "fuzzy search and view the log"},
				\ {"Leaderf git log --directly":               "view the logs directly"},
				\ {"Leaderf git log --explorer":               "fuzzy search and view the log in an explorer tabpage"},
				\ {"Leaderf git log --explorer --unified":     "fuzzy search and view the log in an explorer tabpage, the diffs is shown in unified view"},
				\ {"Leaderf git log --explorer --navigation-position bottom": "specify the position of navigation panel in explorer tabpage"},
				\ {"Leaderf git log --current-file":           "fuzzy search and view the log of current file"},
				\ {"Leaderf git log --current-file --explorer":"fuzzy search and view the log of current file in explorer tabpage"},
				\ {"Leaderf git log --current-line":           "fuzzy search and view the log of current line"},
				\ {"Leaderf git log --current-line --explorer":"fuzzy search and view the log of current line in explorer tabpage"},
				\ {"Leaderf git blame":                        "git blame current file"},
				\ {"Leaderf git blame -w":                     "ignore whitespace when git blame current file"},
				\ {"Leaderf git blame --date relative":        "show relative date when git blame current file"},
				\ {"LeaderfGitInlineBlameEnable":              "Enable inline blame. This command is a shortcut of `:Leaderf git blame --inline`."},
				\ {"LeaderfGitInlineBlameDisable":             "Disable inline blame."},
				\ {"LeaderfGitInlineBlameToggle":              "Toggle inline blame."},
				\ {"LeaderfGitInlineBlameUpdate":              "If the file is updated in the git repository, we need to use this command to update the inline blame."},
				\ ]
	let g:Lf_GitKeyMap = {
				\ 'previous_change': '[c',
				\ 'next_change': ']c',
				\ 'edit_file': '<CR>',
				\ }
	nnoremap <leader>g :<C-u>LeaderfGit<cr>
	"}}}
	" Rg {{{
	if executable('rg')
		let g:Lf_Rg = exepath('rg')
	else
		let g:Lf_Rg = 'C:\Programs\scoop\apps\ripgrep\13.0.0\rg.exe'
	endif
	let g:Lf_RgConfig = [
				\ "--max-columns=150",
				\ '--type-add "web:*.{html,css,js}*"',
				\ "--glob=!git/*",
				\ "--hidden"
				\ ]
	" search word under cursor, the pattern is treated as regex, and enter normal mode directly
	noremap <C-F> :<C-U><C-R>=printf("Leaderf! rg -e %s ", expand("<cword>"))<CR>
	" search word under cursor, the pattern is treated as regex,
	" append the result to previous search results.
	noremap <C-G> :<C-U><C-R>=printf("Leaderf! rg --append -e %s ", expand("<cword>"))<CR>
	" search word under cursor literally only in current buffer
	noremap <C-B> :<C-U><C-R>=printf("Leaderf! rg -F --current-buffer -e %s ", expand("<cword>"))<CR>
	" search word under cursor literally in all listed buffers
	noremap <C-D> :<C-U><C-R>=printf("Leaderf! rg -F --all-buffers -e %s ", expand("<cword>"))<CR>
	" search visually selected text literally, don't quit LeaderF after accepting an entry
	xnoremap gf :<C-U><C-R>=printf("Leaderf! rg -F --stayOpen -e %s ", leaderf#Rg#visual())<CR>
	" recall last search. If the result window is closed, reopen it.
	noremap go :<C-U>Leaderf! rg --recall<CR>
	" " search word under cursor in *.h and *.cpp files.
	" noremap <Leader>a :<C-U><C-R>=printf("Leaderf! rg -e %s -g *.h -g *.cpp", expand("<cword>"))<CR>
	" " the same as above
	" noremap <Leader>a :<C-U><C-R>=printf("Leaderf! rg -e %s -g *.{h,cpp}", expand("<cword>"))<CR>
	" " search word under cursor in cpp and java files.
	" noremap <Leader>b :<C-U><C-R>=printf("Leaderf! rg -e %s -t cpp -t java", expand("<cword>"))<CR>
	" " search word under cursor in cpp files, exclude the *.hpp files
	" noremap <Leader>c :<C-U><C-R>=printf("Leaderf! rg -e %s -t cpp -g !*.hpp", expand("<cword>"))<CR>
	"}}}
endif
"}}}

" Lsp:{{{
try
	let g:lsp_enabled = v:false
	if exists('g:lsp_enabled') && g:lsp_enabled 
		packadd vim-lsp
		packadd vim-lsp-settings
	endif
endtry
if exists('g:lsp_loaded')
	if executable('pylsp')
		" pip install python-lsp-server
		au User lsp_setup call lsp#register_server({
					\ 'name': 'pylsp',
					\ 'cmd': {server_info->['pylsp']},
					\ 'allowlist': ['python'],
					\ })
	endif

	function! s:on_lsp_buffer_enabled() abort
		setlocal omnifunc=lsp#complete
		setlocal signcolumn=yes
		if exists('+tagfunc') | setlocal tagfunc=lsp#tagfunc | endif
		nmap <buffer> gd <plug>(lsp-definition)
		nmap <buffer> gs <plug>(lsp-document-symbol-search)
		nmap <buffer> gS <plug>(lsp-workspace-symbol-search)
		nmap <buffer> gr <plug>(lsp-references)
		nmap <buffer> gi <plug>(lsp-implementation)
		nmap <buffer> gt <plug>(lsp-type-definition)
		nmap <buffer> <F2> <plug>(lsp-rename)
		nmap <buffer> [g <plug>(lsp-previous-diagnostic)
		nmap <buffer> ]g <plug>(lsp-next-diagnostic)
		nmap <buffer> K <plug>(lsp-hover)
		nnoremap <buffer> <expr><c-f> lsp#scroll(+4)
		nnoremap <buffer> <expr><c-d> lsp#scroll(-4)

		let g:lsp_format_sync_timeout = 1000
		autocmd! BufWritePre *.rs,*.go call execute('LspDocumentFormatSync')

		" refer to doc to add more commands
	endfunction

	augroup lsp_install
		au!
		" call s:on_lsp_buffer_enabled only for languages that has the server registered.
		autocmd User lsp_buffer_enabled call s:on_lsp_buffer_enabled()
	augroup END

endif
if exists('g:loaded_lsp_settings')
	let g:lsp_fold_enabled = 1
	set foldmethod=expr
				\ foldexpr=lsp#ui#vim#folding#foldexpr()
				\ foldtext=lsp#ui#vim#folding#foldtext()
	let g:lsp_signs_enabled = 1         		" enable signs
	let g:lsp_diagnostics_echo_cursor = 1 		" enable echo under cursor when in normal mode
	let g:lsp_diagnostics_enabled = 0
	let g:lsp_settings = {
				\	'tex': [
				\		{
				\			'url': 'https://github.com/latex-lsp/texlab',
				\			'description': 'An implementation of Language Server Protocol for LaTeX ', 
				\ 			'requires': [],
				\			'command': 'texlab'
				\		},
				\	]
				\ }
	" \		{
	" \			'url': 'https://github.com/astoff/digestif',
	" \			'description': 'An implementation of Language Server for LaTeX and Others', 
	" \ 			'requires': ['luarocks'],
	" \			'command': 'digestif'
	" \		}
endif
"}}}

" Matlab {{{
" python 2.7{{{
let g:python27_executable = get(g:, 'python27_executable', [
			\ 'C:\Programs\Python\python2.7.16-x64\python.exe',
			\ 'C:\Programs\Python\2.7.16-x64\python.exe',
			\ ])
" \ 'C:\Programs\Python\2.7.16-x86\python.exe',
call filter(g:python27_executable, 'filereadable(v:val)')
if !empty(g:python27_executable)
	let &pythonhome = fnamemodify(python27_executable[0], ':p:h')
	let $PATH = &pythonhome . ';' . $PATH
	" let &pythondll = 'python27.dll'
	if has('python')
		" echo &pythondll
		py import vim
	else
		echoerr 'python27 can not be loaded!' 
	endif
endif
"}}}
let g:matvim_auto_connect=1
let g:matvim_auto_start=0
let g:matvim_max_outputchars = 1000
try
	packadd matvim
	packadd vim-matlab
endtry
"}}}

" NERDTree{{{
try
	packadd nerdtree
endtry
if get(g:, 'loaded_nerd_tree', 0)
	nnoremap <leader>t 	:<C-u>NERDTree<cr>
endif
"}}}

" nrrwrgn{{{
try
	packadd NrrwRgn
endtry
if exists("g:loaded_nrrw_rgn")
endif
"}}}

" Pandoc:{{{
try
	packadd vim-pandoc
	packadd vim-pandoc-syntax
endtry
if exists('g:pandoc#loaded') && g:pandoc#loaded 
endif
"}}}

" Plug:{{{
try
	let plug_plugin_root = expand('~\vimfiles\pack\github.com\opt\vim-plug')
	let &rtp = &rtp . ',' . plug_plugin_root
	runtime! plug.vim
	packadd vim-plug
endtry
if get(g:, 'loaded_plug', 0)
	let g:git_proxy_prefix = 'https://mirror.ghproxy.com/https://github.com/'
	call plug#begin('~\vimfiles\pack\github.com\opt')
	" fzf native plugin
	Plug 'junegunn/fzf'
	" fzf.vim
	Plug 'junegunn/fzf.vim'
	Plug 'JeroenMulkers/matvim'
	Plug 'jpalardy/vim-slime'
	Plug 'junegunn/vim-plug'
	Plug 'kana/vim-textobj-user'
	Plug 'leafOfTree/vim-project'
	Plug 'ludovicchabant/vim-gutentags'
	Plug 'lukelbd/vim-tabline'
	Plug 'MattesGroeger/vim-bookmarks'
	Plug 'neoclide/coc.nvim', {'branch': 'master', 'do': 'yarn install --frozen-lockfile'}
	Plug 'neoclide/coc-tsserver', {'do': 'yarn install --frozen-lockfile'}
	Plug 'preservim/nerdtree'
	Plug 'vimoutliner/vimoutliner'
	Plug 'https://gitee.com/tbq-vim/vim-gutentags.git'
	Plug 'vim-scripts/NrrwRgn'
	Plug 'abbiekressner/vim-matlab'
	Plug 'Yggdroot/LeaderF'
	Plug 'voldikss/LeaderF-everything'
	Plug 'linjiX/LeaderF-git'
	call plug#end()
	" PlugInstall
endif
"}}}

" Project:{{{
try
	if !exists(':ProjectList')
		packadd vim-project
	endif
endtry
if exists(':ProjectList')
	nnoremap <leader>p :ProjectList<cr>
endif
"}}}

" ProjectRoot:{{{
try
	packadd vim-projectroot
endtry
if exists('loaded_projectroot')
	nnoremap <leader>. :ProjectRootCD<cr>
	" Change current working directory
	nnoremap <leader>dp :ProjectRootCD<cr>
	" Automatically whenever you open a buffer: 
	function! <SID>AutoProjectRootCD()
		try
			if &ft != 'help'
				ProjectRootCD
			endif
		catch
			" Silently ignore invalid buffers
		endtry
	endfunction
	autocmd BufEnter * call <SID>AutoProjectRootCD()
	" Edit a file relative to the project root~
	" By changing current directory: >
	nnoremap <leader>eq :ProjectRootCD<cr>:e<space>
	" Without changing the current directory: >
	nnoremap <expr> <leader>ep ':e '.projectroot#guess().'/'
	nnoremap <silent> [p :ProjectBufPrev<cr>
	nnoremap <silent> ]p :ProjectBufNext<cr>
	nnoremap <silent> [P :ProjectBufFirst<cr>
	nnoremap <silent> ]P :ProjectBufLast<cr>
	nnoremap <silent> ]v :ProjectBufNext ~/vimfiles<cr>
	nnoremap <silent> [v :ProjectBufPrev ~/vimfiles<cr>
	nnoremap <silent> ]f :ProjectBufNext 'F<cr>
	nnoremap <silent> [f :ProjectBufPrev 'F<cr>
	nnoremap <silent> <Leader>eg :ProjectRootExe grep<space>
	nnoremap <silent> <leader>ef :exe 'CtrlP' projectroot#guess("'F")<cr>
	nnoremap <silent> <leader>ep :exe 'CtrlP' projectroot#guess()<cr>
endif
"}}}

" slime:{{{
if exists('g:loaded_slime') && g:loaded_slime
	let g:slime_target = "vimterminal"
endif
"}}}

" Startify:{{{
if !exists('g:loaded_startify')
	try
		packadd vim-startify
	endtry
endif
let g:startify_bookmarks = [ {
			\ 	'p': '~\vimfiles\plugin\pack.vim',
			\ }, {
			\ 	'v': '~/vimfiles/plugin/variables.vim'
			\ },
			\	'~/.zshrc'
			\ ]
let g:startify_commands = [
			\ ['PlugInstall', 'install plugins'],
			\ ':help reference',
			\ ['Vim Reference', 'h ref'],
			\ {'h': 'h ref'},
			\ ]
let g:startify_change_to_dir = 1
let g:startify_change_to_vcs_root = 1
let g:startify_change_cmd = 'lcd'
"   |g:startify_custom_header|
let g:startify_custom_header_quotes = ''
let g:startify_enable_special = 1
let g:startify_enable_unsafe = 0
let g:startify_files_number = 10
let g:startify_fortune_use_unicode = 1
"   |g:startify_list_order|
"   |g:startify_lists|
let g:startify_padding_left = 3
let g:startify_relative_path = 1
let g:startify_use_env = 1
"   |g:startify_skiplist|
let g:startify_skiplist_server = [ 'GVIM' ]
let g:startify_update_oldfiles = 1
let g:startify_session_autoload = 0
let g:startify_session_before_save = [ 'silent! tabdo NERDTreeClose' ]
let g:startify_session_delete_buffers = 1
let g:startify_session_persistence = 0
let g:startify_session_remove_lines = ['setlocal', 'winheight']
let g:startify_session_savecmds = []
let g:startify_session_savevars = [
			\ 'g:startify_session_savevars',
			\ 'g:startify_session_savecmds',
			\ 'g:random_plugin_use_feature'
			\ ]
let g:startify_session_sort = 1
if exists('g:loaded_startify') && g:loaded_startify
	nnoremap <m-h> :Startify<cr>
endif
"}}}

" gutentags{{{
try
	packadd vim-gutentags
	if exists('g:loaded_gutentags') && g:loaded_gutentags
		" gutentags搜索工程目录的标志，碰到这些文件/目录名就停止向上一级目录递归 "
		let g:gutentags_project_root = ['.root', '.svn', '.git', '.project']

		" 所生成的数据文件的名称 "
		let g:gutentags_ctags_tagfile = '.tags'

		" 同时开启 ctags 和 gtags 支持：
		let g:gutentags_modules = []
		if executable('ctags')
			let g:gutentags_modules += ['ctags']
		endif
		if executable('gtags-cscope') && executable('gtags')
			let g:gutentags_modules += ['gtags_cscope']
		endif

		" 将自动生成的 tags 文件全部放入 ~/.cache/tags 目录中，避免污染工程目录 "
		let s:vim_tags = expand('~/.cache/tags')
		let g:gutentags_cache_dir = s:vim_tags
		" 检测 ~/.cache/tags 不存在就新建 "
		if !isdirectory(s:vim_tags)
			silent! call mkdir(s:vim_tags, 'p')
		endif

		" 配置 ctags 的参数 "
		let g:gutentags_ctags_extra_args = ['--fields=+niazS', '--extra=+q']
		let g:gutentags_ctags_extra_args += ['--c++-kinds=+pxI']
		let g:gutentags_ctags_extra_args += ['--c-kinds=+px']
	endif
endtry
"}}}

" Tabline{{{
let g:tabline_skip_filetypes = ['diff', 'help', 'man', 'qf']
let g:tabline_maxlength = 13
try
	packadd vim-tabline
endtry
if exists('g:loaded_tabline')
endif
"}}}

" textobj: {{{
try
	packadd vim-textobj-entire    " e
	packadd vim-textobj-function  " f / F
	packadd vim-textobj-indent    " i
	packadd vim-textobj-parameter " ,
	packadd vim-textobj-syntax    " y
	packadd vim-textobj-user      " d t A l (
catch 
	echoerr v:exception
endtry
if exists('*textobj#user#plugin()')
	call textobj#user#plugin('datetime', {
				\   'date': {
				\     'pattern': '\<\d\d\d\d-\d\d-\d\d\>',
				\     'select': ['ad', 'id'],
				\   },
				\   'time': {
				\     'pattern': '\<\d\d:\d\d:\d\d\>',
				\     'select': ['at', 'it'],
				\   },
				\ })
	call textobj#user#plugin('braces', {
				\   'angle': {
				\     'pattern': ['<<', '>>'],
				\     'select-a': 'aA',
				\     'select-i': 'iA',
				\   },
				\ })
	call textobj#user#plugin('line', {
				\   '-': {
				\     'select-a-function': 'CurrentLineA',
				\     'select-a': 'al',
				\     'select-i-function': 'CurrentLineI',
				\     'select-i': 'il',
				\   },
				\ })
	function! CurrentLineA()
		normal! 0
		let head_pos = getpos('.')
		normal! $
		let tail_pos = getpos('.')
		return ['v', head_pos, tail_pos]
	endfunction

	function! CurrentLineI()
		normal! ^
		let head_pos = getpos('.')
		normal! g_
		let tail_pos = getpos('.')
		let non_blank_char_exists_p = getline('.')[head_pos[2] - 1] !~# '\s'
		return
					\ non_blank_char_exists_p
					\ ? ['v', head_pos, tail_pos]
					\ : 0
	endfunction

	call textobj#user#plugin('tex', {
				\   'paren-math': {
				\     'pattern': ['\\left(', '\\right)'],
				\     'select-a': [],
				\     'select-i': [],
				\   },
				\	'environment': {
				\		'pattern': ['\\begin{.*}', '\\end{.*}'],
				\     	'select-a': [],
				\     	'select-i': [],
				\	},
				\ })

	augroup tex_textobjs
		autocmd!
		autocmd FileType tex call textobj#user#map('tex', {
					\   'paren-math': {
					\     'select-a': '<buffer> a(',
					\     'select-i': '<buffer> i(',
					\   },
					\	  'environment': {
					\     'select-a': '<buffer> a{',
					\     'select-i': '<buffer> i{',
					\   },
					\ })
	augroup END
endif
"}}}

" terminal_help:{{{
try
	packadd vim-terminal-help
endtry
"}}}

" Unimpaired:{{{
try
	packadd vim-unimpaired
endtry
if exists("g:loaded_unimpaired")
endif
"}}}

" Unite:{{{
let g:unite_source_outline_info = get(g:, 'unite_source_outline_info', {})
let g:unite_source_outline_info.matlab = {
			\	'heading': '^\s*\(classdef\|properties\|methods\|function\|end\s%\s\%(classdef\|properties\|methods\|function\)\)\s*\|^%%\s'
			\ }
try
	packadd unite.vim
	packadd unite-outline
	nnoremap <m-o>	:Unite outline<cr>
endtry
if get(g:, 'loaded_unite', 0)
	nnoremap <m-k>	:Unite -start-insert mapping<cr>
	packadd neomru.vim
	if get(g:, 'loaded_neomru', 0)
		nnoremap <m-r>	:Unite -start-insert file_mru directory_mru<cr>
	endif
endif
"}}}

" UltiSnips:{{{
try
	packadd ultisnips
endtry
let g:UltiSnipsEditSplit = 'tabdo'
let g:UltiSnipsSnippetDirectories = ['UltiSnips']
let g:UltiSnipsSnippetStorageDirectoryForUltiSnipsEdit = '~\vimfiles\Ultisnips'
let g:UltiSnipsEnableSnipMate = 1
let g:UltiSnipsExpandTrigger = '<tab>'
" let g:UltiSnipsListSnippets =  '<c-tab>'
let g:UltiSnipsJumpForwardTrigger = '<c-j>'
let g:UltiSnipsJumpBackwardTrigger = '<c-k>'
inoremap <c-x><c-k> <c-x><c-k>
let g:UltiSnipsExpandOrJumpTrigger = "<tab>"
" let g:UltiSnipsJumpOrExpandTrigger = "<tab>"
" let g:ulti_expand_or_jump_res = 0 "default value, just set once
" function! Ulti_ExpandOrJump_and_getRes()
" 	call UltiSnips#ExpandSnippetOrJump()
" 	return g:ulti_expand_or_jump_res
" endfunction
" inoremap <NL> <C-R>=(Ulti_ExpandOrJump_and_getRes() > 0)?"":IMAP_Jumpfunc('', 0)<CR>
"}}}

" vimcdoc:{{{
try
	packadd vimcdoc
endtry
"}}}

" VimFiler:{{{
try
	packadd vimfiler.vim
endtry
if get(g:, 'loaded_vimfiler', 0)
	nnoremap <m-e>	:VimFilerBufferDir -explorer<cr>
	nnoremap <leader>ev	:VimFilerExplorer<cr>
	nnoremap <leader>v	:VimFilerBufferDir -explorer<cr>
	nnoremap <m-v>	:VimFilerBufferDir<cr>
endif
"}}}

" VimTeX:{{{
try
	packadd vimtex
endtry
if get(g:, 'loaded_vimtex', 0)
	let g:vimtex_enabled = v:true
	let g:tex_flavor='latex'
	let g:tex_conceal='abdmg'
	let g:vimtex_texcount_custom_arg=' -ch -total'
	let g:vimtex_delim_list = get(g:, 'vimtex#delim#lists', {})
	let g:vimtex_mappings_enabled = 1
	au FileType tex map <buffer> <silent>  <localleader>lw :VimtexCountWords!  <CR><CR>
	let g:Tex_ViewRule_pdf = 'SumatraPDF -reuse-instance -inverse-search "gvim - c \":RemoteOpen +\%l \%f\""'
	if executable('latexmk')
		let g:vimtex_compiler_latexmk_executable = exepath('latexmk')
	endif
	let g:vimtex_compiler_latexmk_executable = get(g:, 'vimtex_compiler_latexmk_executable', 'C:\Programs\texlive\2023\bin\windows\latexmk.exe')
	if !executable(g:vimtex_compiler_latexmk_executable)
		let $PATH='C:\Program Files\texlive\2023\bin\windows;'.$PATH
		if executable('latexmk')
			let g:vimtex_compiler_latexmk_executable = exepath('latexmk')
		else
			if executable('C:\\Program\ Files\\texlive\\2023\\bin\\windows\\latexmk.exe')
				let g:vimtex_compiler_latexmk_executable = executable('latexmk') ? exepath('latexmk') : 'C:\\Program\ Files\\texlive\\2023\\bin\\windows\\latexmk.exe'
			endif
		endif
	endif
	let g:vimtex_view_general_viewer = get(g:, 'vimtex_view_general_viewer', 'SumatraPDF')
	if !executable(g:vimtex_view_general_viewer)
		let $PATH='C:\Program Files\SumatraPDF;'.$PATH
		let g:vimtex_view_general_viewer = executable('SumatraPDF') ? exepath('SumatraPDF') : fnameescape("C:\\Program Files\\SumatraPDF\\SumatraPDF.exe")
	endif

	" latexrun
	if executable('latexrun')
		let g:vimtex_compiler_method = 'latexrun'
		let g:vimtex_compiler_latexrun_engines = {
					\ '_'                : 'pdflatex',
					\ 'pdflatex'         : 'pdflatex',
					\ 'lualatex'         : 'lualatex',
					\ 'xelatex'          : 'xelatex',
					\}
	endif
	" latexmk
	if executable('latexmk') || executable(g:vimtex_compiler_latexmk_executable)
		let g:vimtex_compiler_method = 'latexmk'
		let g:vimtex_compiler_latexmk = {
					\ 'aux_dir' : '',
					\ 'out_dir' : '',
					\ 'build_dir': 'pdf',
					\ 'callback': 1,
					\ 'continous': 1,
					\ 'executable': g:vimtex_compiler_latexmk_executable,
					\ 'hooks' : [],
					\ 'options' : [
					\   '-verbose',
					\   '-file-line-error',
					\   '-synctex=1',
					\   '-interaction=nonstopmode',
					\ ] ,
					\}
		let g:vimtex_compiler_latexmk_engines = {
					\ '_'                : '-pdf',
					\ 'pdflatex'         : '-pdf',
					\ 'dvipdfex'         : '-pdfdvi',
					\ 'lualatex'         : '-lualatex',
					\ 'xelatex'          : '-xelatex',
					\ 'context (pdftex)' : '-pdf -pdflatex=texexec',
					\ 'context (luatex)' : '-pdf -pdflatex=context',
					\ 'context (xetex)'  : "-pdf -pdflatex='texexec --xtx'",
					\}
	endif
	" viewer
	let g:vimtex_view_method='general'
	if executable('SumatraPDF')
		let g:vimtex_view_general_viewer = 'SumatraPDF'
	else
		let g:vimtex_view_general_viewer = 'C:\Programs\SumatraPDF\SumatraPDF.exe'
	endif
	" let g:vimtex_view_general_options_latexmk = '-reuse-instance'
	let g:vimtex_view_general_options
				\ = ' -reuse-instance -forward-search @tex @line @pdf'
				\ . ' -inverse-search "' . 'cmd /c start /min \"\" ' . exepath(v:progpath)
				\ . ' -v --not-a-term -T dumb -c \"VimtexInverseSearch %l ''%f''\""' 
	let g:vimtex_quickfix_open_on_warning=0
	let g:vimtex_quickfix_mode=1
endif
"}}}

" VimTweak{{{
try
	packadd vimtweak
catch /.*/
endtry
" }}}

" WhichKey:{{{
let g:which_key_hspace = 5
let g:mapleader = get(g:, 'mapleader', ',')
let g:leader_keymap = get(g:, 'leader_keymap', { 'name'  : '+leader' })
let g:leader_keymap.a = { 'name'  : '+asynctask'           , 
			\               'e'     :   [ 'AsyncTaskEdit'     , 'edit'           ],
			\               'g'     :   [ 'AsyncTaskLast'     , 'last'           ],
			\               'l'     :   [ 'AsyncTaskList'     , 'list'           ],
			\               'm'     :   [ 'AsyncTaskMacro'    , 'macro'          ],
			\               'p'     :   [ 'AsyncTaskProfile'  , 'profile'        ],
			\               'v'     :   [ 'AsyncTaskEnv'      , 'environment'    ],
			\             }
let g:leader_keymap.b = {   'name' : '+buffer' ,
			\ '1' : ['b1'           , 'buffer 1']        ,
			\ '2' : ['b2'           , 'buffer 2']        ,
			\ 'd' : ['bd'           , 'delete-buffer']   ,
			\ 'e' : ['BufExplorer'  , 'buffer-explorer'] ,
			\ 'f' : ['bfirst'       , 'first-buffer']    ,
			\ 'h' : ['Startify'     , 'home-buffer']     ,
			\ 'l' : ['blast'        , 'last-buffer']     ,
			\ 'n' : ['bnext'        , 'next-buffer']     ,
			\ 'p' : ['bprevious'    , 'previous-buffer'] ,
			\ '?' : ['Buffers'      , 'fzf-buffer']      ,
			\ }
let g:leader_keymap.f = { 'name'  : '+file',
			\ 's': ['update', 'save-file'],
			\ }
let g:leader_keymap.o = { 'name'  : '+open' ,
			\ 'q': ['copen', 'open-quickfix'],
			\ 'l': ['lopen', 'open-locationlist'],
			\ }
let g:leader_keymap.l = {    'name': '+leaderf',
			\               'b'    : [ 'LeaderfBuffer'              , 'buffer'          ],
			\               'c'    : [ 'LeaderfCommand'             , 'command'         ],
			\               'C'    : [ 'LeaderfColorscheme'         , 'colorscheme'     ],
			\               'f'    : [ 'LeaderfFile'                , 'file'            ],
			\               'F'    : [ 'LeaderfFunction'            , 'function'        ],
			\               'g'    : [ 'LeaderfRgInteractive'       , 'grep'            ],
			\               'h'    : [ 'LeaderfHelp'                , 'help'            ],
			\               'j'    : [ 'Leaderf jumps'              , 'jumps'           ],
			\               'l'    : [ 'LeaderfLine'                , 'line'            ],
			\               'L'    : [ 'LeaderfLocList'             , 'location'        ],
			\               'q'    : [ 'LeaderfQuickFix'            , 'quickfix'        ],
			\               'r'    : [ 'LeaderfMru'                 , 'recent'          ],
			\               's'    : [ 'LeaderfSelf'                , 'leaderf'         ],
			\               'w'    : [ 'LeaderfWindow'              , 'window'          ],
			\ }
let g:leader_keymap.L = {   'name' : '+lsp'                                            ,
			\ 'f' : ['LanguageClient#textDocument_formatting()'     , 'formatting'] ,
			\ 'h' : ['LanguageClient#textDocument_hover()'          , 'hover'] ,
			\ 'r' : ['LanguageClient#textDocument_references()'     , 'references'] ,
			\ 'R' : ['LanguageClient#textDocument_rename()'         , 'rename'] ,
			\ 's' : ['LanguageClient#textDocument_documentSymbol()' , 'document-symbol']  ,
			\ 'S' : ['LanguageClient#workspace_symbol()'            , 'workspace-symbol'] ,
			\ 'g' : {
			\ 'name': '+goto',
			\ 'd' : ['LanguageClient#textDocument_definition()'     , 'definition']       ,
			\ 't' : ['LanguageClient#textDocument_typeDefinition()' , 'type-definition']  ,
			\ 'i' : ['LanguageClient#textDocument_implementation()'  , 'implementation']   ,
			\ },
			\ }
let g:leader_keymap.u = { 'name': '+unite', 
			\   'B': [':Unite bookmark'	    , 'bookmark' 	],                  
			\   'b': [':Unite buffer buffer_tab'	    , 'buffer' 	    ],                    
			\   'C': [':Unite change'	    , 'change' 	    ],                    
			\   'c': [':Unite command'	    , 'command' 	],                   
			\   'd': [':Unite directory'	, 'directory' 	],                 
			\   'D': {  'name'  : '+directory',
			\           'n'     : [':Unite directory/new'	    , 'directory/new' 	        ],             
			\           'r'     : [':Unite directory_rec'	    , 'directory_rec' 	        ],             
			\           'a'     : [':Unite directory_rec/async'	, 'directory_rec/async' 	],       
			\       }, 
			\   'f': {  'name'  : '+file',
			\           'a'     : [':Unite file/async'	        , 'async' 	 	         	],                      
			\           'n'     : [':Unite file/new'	        , 'file/new' 	         	],                  
			\           'l'     : [':Unite file_list'	        , 'file_list' 	         	],                 
			\           'p'     : [':Unite file_point'	        , 'file_point' 	         	],                
			\           'r'     : [':Unite file_rec'	        , 'file_rec' 	         	],                  
			\           'A'     : [':Unite file_rec/async'	    , 'file_rec/async' 	        ],            
			\           'G'     : [':Unite file_rec/git'	    , 'file_rec/git' 	        ],              
			\           'N'     : [':Unite file_rec/neovim'	    , 'file_rec/neovim' 	    ],           
			\       }, 
			\   'F': [':Unite function'	, 'function' 	],                  
			\   'g': [':Unite grep'	    , 'grep' 	    ],                     
			\   'G': [':Unite grep/git'	, 'grep/git' 	],                  
			\   'h': {  'name' : '+history',
			\           'c': [':Unite history/command'	 	    , 'history/command' 	],           
			\           's': [':Unite history/search'	 	    , 'history/search' 		],            
			\           'u': [':Unite history/unite'	 	    , 'history/unite' 		],             
			\       }, 
			\   'j': [':Unite jump'	                            , 'jump' 	    ],                      
			\   'J': [':Unite jump_point'	                    , 'jump_point' 	],                
			\   'l': [':Unite launcher'	                        , 'launcher' 	],                  
			\   'L': [':Unite line'	                            , 'line' 	 	],                     
			\   'm': [':Unite mapping'	                        , 'mapping' 	],                   
			\   'M': [':Unite menu'	                            , 'menu' 	 	],                      
			\   'n': {  'name'  : '+neosnippet',
			\           's'     : [':Unite neosnippet'	        , 'neosnippet' 	        ],               
			\           'r'     : [':Unite neosnippet/runtime'	, 'neosnippet/runtime' 	],        
			\           'u'     : [':Unite neosnippet/user'	    , 'neosnippet/user' 	],           
			\       }, 
			\   '!': [':Unite output'	        , 'output' 	 	 	 	 		],                    
			\   '~': [':Unite output/shellcmd'	, 'output/shellcmd' 	 		],           
			\   'p': [':Unite process'	        , 'process' 	 	 	 		],                   
			\   'r': [':Unite register'	        , 'register' 	 	 	 		],                  
			\   'R': [':Unite resume'	        , 'resume' 	 	 	 			],                    
			\   '$': [':Unite runtimepath'	    , 'runtimepath' 	 	 		],               
			\   's': [':Unite script'	        , 'script' 	 	 	 			],                   
			\   'S': [':Unite source'	        , 'source' 	 	 	 			],                    
			\   't': [':Unite tab'	            , 'tab' 	 	 	 			],                       
			\   'u': [':Unite ultisnips'	    , 'ultisnips' 	 	 	 		],                
			\   'v': [':Unite vim_bookmarks'	, 'vim_bookmarks' 	 	 		],             
			\   '/': [':Unite vimgrep'	        , 'vimgrep' 	 	 	 		],                  
			\   'w': [':Unite window'	        , 'window' 	 	 	 			],                    
			\ }
let g:leader_keymap.w = { 'name': '+vimwiki', 
			\	'b': ['<Plug>Vimwiki2HTMLBrowse', 'browse'],
			\	'i': ['<Plug>VimwikiIndex', 'index'],
			\   'I': ['<Plug>VimwikiTabIndex', 'index-tab'],
			\   's': ['<Plug>VimwikiUISelect', 'select'],
			\	'f': ['<Plug>VimwikiFollowLink', 'follow'],
			\	'S': ['<Plug>VimwikiSplitLink', 'split'],
			\	'h': ['<Plug>Vimwiki2HTML', 'html'],
			\	'g': ['<Plug>VimwikiDiaryGenerateLinks', 'generate'],
			\	'd': ['<Plug>VimwikiDiaryIndex', 'diary'],
			\	'n': ['<Plug>VimwikiMakeDiaryNote', 'note'],
			\	'N': ['<Plug>VimwikiTabMakeDiaryNote', 'note'],
			\	'y': ['<Plug>VimwikiMakeYesterdayDiaryNote', 'yesterday'],
			\	'm': ['<Plug>VimwikiMakeTomorrowDiaryNote', 'tommorrow'],
			\ }
try
	packadd vim-which-key
endtry
if exists('g:loaded_vim_which_key')
	call which_key#register(' ', 'g:leader_keymap')
	nnoremap <Space> :<C-U>WhichKey ' '<CR>
	let g:leader_keymap_visual = get(g:, 'leader_keymap_visual', {})
	" call which_key#register('<leader>', 'g:leader_keymap_visual')
endif
"}}}

" VimWiki:{{{
let g:vimwiki_filetypes = []
if !exists("g:loaded_vimwiki")
	try
		packadd vimwiki
	endtry
endif
if exists("g:vimwiki_wikilocal_vars")
	let wiki = g:vimwiki_wikilocal_vars[0]
	let wiki.path = expand('~\vimfiles\vimwiki\')
	let g:vimwiki_wikilocal_vars[0] = wiki
	let g:vimwiki_list = [wiki]
endif
if exists("g:loaded_vimwiki")
	" global mapping
	nmap <Leader>ww 			<Plug>VimwikiIndex
	nmap <Leader>wt 			<Plug>VimwikiTabIndex
	nmap <Leader>ws 			<Plug>VimwikiUISelect
	nmap <Leader>wi 			<Plug>VimwikiDiaryIndex
	nmap <Leader>w<Leader>w 	<Plug>VimwikiMakeDiaryNote
	nmap <Leader>w<Leader>t 	<Plug>VimwikiTabMakeDiaryNote
	nmap <Leader>w<Leader>y 	<Plug>VimwikiMakeYesterdayDiaryNote
	nmap <Leader>w<Leader>m 	<Plug>VimwikiMakeTomorrowDiaryNote
	" local mapping
	nmap <Leader>wh         	<Plug>Vimwiki2HTML
	nmap <Leader>whh         	<Plug>Vimwiki2HTMLBrowse

	function! VimwikiLinkHandler(link)
		try
			let link = a:link
			if link =~# 'https\?://'
				if executable('C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe')
					let browser = exepath('C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe')
					silent execute '!start "'.browser.'" ' . a:link
					return 1
				endif
			endif
			let pwd = fnamemodify(bufname('%'), ':p:h')
			let filename = expand(pwd . '/' . link)
			if filename !~# '.*\.wiki'
				let filename = filename . '.wiki'
			endif
			execute 'edit ' . filename
			return 1
		catch
			echoerr v:exception
		endtry
		return 0
	endfunction
endif
"}}}

" VOom:{{{
try
	packadd VOoM
endtry
"}}}

" Airline:{{{
" \ 'battery', 
" \ 'bookmark', 
" \ 'bufferline', 
" \ 'capslock', 
" \ 'codeium', 
" \ 'commandt', 
" \ 'csv', 
" \ 'default', 
" \ 'denite', 
" \ 'dirvish', 
" \ 'eclim', 
" \ 'example', 
" \ 'fern', 
" \ 'fugitiveline', 
" \ 'gen_tags', 
" \ 'gina', 
" \ 'grepper', 
" \ 'gutentags', 
" \ 'hunks', 
" \ 'localsearch', 
" \ 'lsp', 
" \ 'neomake', 
" \ 'netrw', 
" \ 'nrrwrgn', 
" \ 'nvimlsp', 
" \ 'obsession', 
" \ 'omnisharp', 
" \ 'promptline', 
" \ 'rufo', 
" \ 'syntastic', 
" \ 'tagbar', 
" \ 'taglist', 
" \ 'tmuxline', 
" \ 'undotree', 
" \ 'unicode', 
" \ 'unite', 
" \ 'vim9lsp', 
" \ 'vimagit', 
" \ 'vimodoro', 
" \ 'vista', 
" \ 'windowswap', 
" \ 'xkblayout', 
" \ 'ycm', 

let g:airline_extensions = [
			\ 'ale', 
			\ 'branch', 
			\ 'bufferline', 
			\ 'coc', 
			\ 'ctrlp', 
			\ 'ctrlspace', 
			\ 'cursormode', 
			\ 'fzf', 
			\ 'keymap', 
			\ 'languageclient', 
			\ 'po', 
			\ 'poetv', 
			\ 'quickfix', 
			\ 'scrollbar', 
			\ 'searchcount', 
			\ 'tabline', 
			\ 'term', 
			\ 'vimcmake', 
			\ 'vimtex', 
			\ 'virtualenv', 
			\ 'whitespace', 
			\ 'wordcount', 
			\ 'zoomwintab', 
			\ ]
" ALE
let g:airline#extensions#disable_rtp_load = 1
let g:airline#extensions#ale#enabled = 1
let airline#extensions#ale#error_symbol = 'E:'
let airline#extensions#ale#warning_symbol = 'W:'
let airline#extensions#ale#show_line_numbers = 1
let airline#extensions#ale#open_lnum_symbol = '(L'
let airline#extensions#ale#close_lnum_symbol = ')'
" Bookmarks
let g:airline#extensions#bookmark#enabled = 1
" Branch
let g:airline#extensions#branch#enabled = 1
let g:airline#extensions#branch#empty_message = ''
let g:airline#extensions#branch#vcs_priority = ["git", "mercurial"]
let g:airline#extensions#branch#use_vcscommand = 0
let g:airline#extensions#branch#displayed_head_limit = 10
" let g:airline#extensions#branch#format = 0
let g:airline#extensions#branch#format = 1
let g:airline#extensions#branch#sha1_len = 10
let g:airline#extensions#branch#vcs_checks = ['untracked', 'dirty']
let g:airline#extensions#bufferline#enabled = 1
let g:airline#extensions#bufferline#overwrite_variables = 1
" CasLock
let g:airline#extensions#capslock#enabled = 1
"Tabline
let g:airline#extensions#tabline#enabled = 1
let g:airline#extensions#tabline#show_splits = 1
let g:airline#extensions#tabline#switch_buffers_and_tabs = 1
let g:airline#extensions#tabline#show_buffers = 1
let g:airline#extensions#tabline#show_tabs = 1
let g:airline#extensions#tabline#show_tab_count = 2
" let g:airline#extensions#tabline#exclude_preview = 1
let g:airline#extensions#tabline#show_tab_nr = 1
let g:airline#extensions#tabline#buf_label_first = 1
let g:airline#extensions#tabline#buffers_label = 'Buffers'
let g:airline#extensions#tabline#tabs_label = 'Tabs'
let airline#extensions#tabline#current_first = 1
if !exists('g:loaded_airline')
	try
		packadd vim-airline
		packadd vim-airline-themes
	endtry
endif
if exists('g:loaded_airline')
	let g:airline#extensions#tabline#buffer_idx_mode = 1
	nmap <leader>1 <Plug>AirlineSelectTab1
	nmap <leader>2 <Plug>AirlineSelectTab2
	nmap <leader>3 <Plug>AirlineSelectTab3
	nmap <leader>4 <Plug>AirlineSelectTab4
	nmap <leader>5 <Plug>AirlineSelectTab5
	nmap <leader>6 <Plug>AirlineSelectTab6
	nmap <leader>7 <Plug>AirlineSelectTab7
	nmap <leader>8 <Plug>AirlineSelectTab8
	nmap <leader>9 <Plug>AirlineSelectTab9
	nmap <leader>0 <Plug>AirlineSelectTab0
	nmap <leader>- <Plug>AirlineSelectPrevTab
	nmap <leader>+ <Plug>AirlineSelectNextTab
	" call airline#init#bootstrap()
	" call airline#extensions#load()
	" AirlineTheme gruvbox
endif
"}}}

